import {
	getAllParentCategory,
	getSubCategoryByParentId
} from '@/api/api';
import {
	getCate
} from '@/utils/getCate'; // 引入 getCate 函数

Component({
	options: {
		addGlobalClass: true, // 启用全局样式类
	},
	properties: {
		// 控制对话框显示/隐藏
		visible: {
			type: Boolean,
			value: false
		},
		// 书籍信息数据
		bookInfo: {
			type: Object,
			value: {
				isbn: '',
				title: '',
				author: '',
				publisher: '',
				publishYear: '',
				parentCategoryId: '',
				categoryId: '',
				parentCategoryName: '',
				categoryName: ''
			},
			observer: function (newVal) {
				// 当 bookInfo 变化时更新显示的分类文本
				console.log(newVal)
				if (newVal?.parentCategoryId) {
					this.loadCategories();
					this.setData({
						parentCategoryText: newVal.parentCategoryName || '',
						subCategoryText: newVal.categoryName || ''
					});
				}
			}
		}
	},

	data: {
		parentCategories: [],
		subCategories: [],
		parentCategoryMap: {}, // 用于存储父分类到子分类的映射
		parentCategoryText: '', // 父分类显示文本
		subCategoryText: '', // 子分类显示文本
		showParentCategoryPicker: false, // 是否显示父分类选择器
		showSubCategoryPicker: false, // 是否显示子分类选择器
	},

	lifetimes: {
	  attached() {
	    console.log(this.data.bookInfo)
	    // 组件实例进入页面节点树时执行
	    this.loadCategories();
	  },
	},

	methods: {
		// 加载分类数据
		async loadCategories() {
			try {
				// 直接调用 getCate 函数获取分类数据
				await getCate();

				// 从全局app实例获取分类数据
				const app = getApp();
				if (app.categoryList && app.categoryList.length > 0) {
					this.processCategoryData(app.categoryList);
				}
			} catch (error) {
				console.error('加载分类数据失败', error);
				// 可以添加错误提示
				wx.showToast({
					title: '分类数据加载失败',
					icon: 'none'
				});
			}
		},

		// 处理分类数据，将其转换为 van-picker 所需的格式
		processCategoryData(categories) {
			const parentCategories = [];
			const parentCategoryMap = {};

			categories.forEach(parent => {
				parentCategories.push({
					text: parent.text,
					value: parent.id
				});
				parentCategoryMap[parent.id] = parent.children.map(child => ({
					text: child.text,
					value: child.id
				}));
			});
			console.log('bookInfo', this.data.bookInfo)
			console.log('cates', parentCategories, '2', parentCategoryMap)
			this.setData({
				parentCategories,
				parentCategoryMap,
				// 初始化显示文本
				parentCategoryText: this.data.bookInfo.parentCategoryId ? parentCategories.find(item => item.value === this.data.bookInfo.parentCategoryId)?.text : '',
				subCategoryText: this.data.bookInfo.categoryId ? parentCategoryMap[this.data.bookInfo.parentCategoryId]?.find(item => item.value === this.data.bookInfo.categoryId)?.text : ''
			});
			console.log('parent', this.data.bookInfo.parentCategoryId)
			// 如果有父分类ID，加载对应的子分类
			if (this.data.bookInfo.parentCategoryId) {
				this.loadSubCategories(this.data.bookInfo.parentCategoryId);
			}
		},

		// 根据父分类ID加载子分类
		loadSubCategories(parentCategoryId) {
			console.log('父分类id', parentCategoryId)
			const subCategories = this.data.parentCategoryMap[parentCategoryId] || [];
			console.log('子分类', subCategories)
			this.setData({
				subCategories: subCategories
			});
		},

		// 字段值改变事件处理
		onFieldChange(e) {
			const {
				field
			} = e.currentTarget.dataset;
			this.setData({
				[`bookInfo.${field}`]: e.detail
			});
		},

		// 父分类选择器点击事件
		onParentCategoryClick() {
			this.setData({
				showParentCategoryPicker: true
			});
			console.log('p', this.data.bookInfo.parentCategoryId)
		},

		// 子分类选择器点击事件
		onSubCategoryClick() {
			this.setData({
				showSubCategoryPicker: true
			});
			console.log('c', this.data.bookInfo.categoryId)
		},

		// 父分类选择器关闭事件
		onParentCategoryPickerClose() {
			this.setData({
				showParentCategoryPicker: false
			});
		},

		// 子分类选择器关闭事件
		onSubCategoryPickerClose() {
			this.setData({
				showSubCategoryPicker: false
			});
		},

		// 父分类确认选择
		onParentCategoryConfirm(e) {
			const {
				value,
				index
			} = e.detail;
			console.log('pv',value,'pi',index)
			const selectedParentCategory = this.data.parentCategories[index].text;
			console.log(selectedParentCategory)
			this.setData({
				'bookInfo.parentCategoryId': value.value,
				'bookInfo.categoryId': null, // 父分类改变时清空子分类
				parentCategoryText: selectedParentCategory||'无名',
				subCategoryText: '', // 清空子分类显示文本
				showParentCategoryPicker: false // 关闭选择器
			});
			this.loadSubCategories(value.value);
		},

		// 子分类确认选择
		onSubCategoryConfirm(e) {
			const {
				value,
				index
			} = e.detail;
			console.log('cv',value,'ci',index)
			const selectedSubCategory = this.data.subCategories[index].text;
			console.log(selectedSubCategory)
			this.setData({
				'bookInfo.categoryId': value.value,
				subCategoryText: selectedSubCategory||'无名',
				showSubCategoryPicker: false // 关闭选择器
			});
		},

		// 确认按钮点击事件
		onConfirm() {
			this.triggerEvent('confirm', this.data.bookInfo);
		},

		// 取消按钮点击事件
		onCancel() {
			this.setData({
				visible: false
			});
			this.triggerEvent('cancel');
		}
	}
});